from pandas.io.data import DataReader
from pandas.io.data import DataFrame
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from datetime import datetime
from datetime import timedelta
import pandas as pd
import numpy as np
import urllib
import codecs
import csv 
import os
import glob
import json
import requests
#from pykalman import UnscentedKalmanFilter



# Only provide the analysis tool, no ticker pick included


def ticker_retrive(ticker):
    data = DataReader(ticker, "yahoo", datetime(2000, 1, 1), datetime.today())
    filename = ticker + ".csv"
    data.to_csv(filename)
    
def ticker_update():
    return
        
def ticker_from_csv(ticker):
    filename = ticker + ".csv"
    df = DataFrame.from_csv(filename)
    return df
    
def ticker_price_av(line):
	line['Open'] = ''



def df_ticker_return(tickerdf):
	'''
	Not good strategy
	'''
	columnName = ['p12','p26','v12','v26', 'pAv']
	ma = pd.DataFrame(index=tickerdf.index, columns=columnName)
	# moving average
	ma['p12'] = pd.rolling_mean(tickerdf['Adj Close'],12, min_periods=2)
	ma['p26'] = pd.rolling_mean(tickerdf['Adj Close'],26, min_periods=2)
	ma['v12'] = pd.rolling_mean(tickerdf['Volume'],12, min_periods=2)
	ma['v26'] = pd.rolling_mean(tickerdf['Volume'],26, min_periods=2)
	# average price 
	ma['gain'] = ma['v12'] - ma['v26']
	ma['gainMA'] = pd.rolling_mean(ma['gain'],5, min_periods=2)
	ma['close'] = tickerdf['Adj Close']*10000
 	ma = ma[-30:]
	N = len(ma)
	ind = np.arange(N)  # the evenly spaced plot indices
	fig, ax = plt.subplots()
	ax.plot(ind, ma['gain'], '-')
	ax.plot(ind, ma['gainMA'],'o-')
	ax.bar(ind, ma['close'])
	def format_date(x, pos=None):
		thisind = np.clip(int(x+0.5), 0, N-1)
		return ma.index[thisind].strftime('%Y-%m-%d')
	ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
	fig.autofmt_xdate()
	plt.show()
	#return ma

def df_ticker_volume(tickerdf):
    tickerdf['VolMA10'] = pd.rolling_mean(tickerDf['Volume'],12, min_periods=2)
    tickerdf['VolMA26'] = pd.rolling_mean(tickerDf['Volume'],26, min_periods=2)
    return tickerdf



def chart_weekly(tickerdf):
	''' Chart for weekly price and volume movement
	'''
	print "weekly chart"

if  __name__ =='__main__':
	ticker = 'amrs'
	#ticker_retrive(ticker)
	tickerdf = ticker_from_csv(ticker);



    